<template>
	<view class="container">
		<view class="status-bar"></view>
		<view class="header">
			<text class="title">新增备件</text>
		</view>

		<view class="form card">
			<view class="field"><text class="label">备件编号</text><input class="input" v-model="form.partNo" placeholder="请输入备件编号" /></view>
			<view class="field"><text class="label">备件名称</text><input class="input" v-model="form.partName" placeholder="请输入备件名称" /></view>
			<view class="field"><text class="label">规格型号</text><input class="input" v-model="form.modelNo" placeholder="请输入规格型号" /></view>
			<view class="field"><text class="label">备件类型</text>
				<picker mode="selector" :range="typeList" range-key="name" @change="onTypeChange"><view class="input picker">{{ typeName || '请选择备件类型' }}</view></picker>
			</view>
			<view class="field"><text class="label">仓库</text>
				<picker mode="selector" :range="warehouseList" range-key="name" @change="onWhChange"><view class="input picker">{{ warehouseName || '请选择仓库' }}</view></picker>
			</view>
			
			<!-- 关联资产部分 -->
			<view class="section">
				<view class="section-title">关联资产</view>
				<view class="asset-list">
					<view class="asset-item" v-for="(asset, index) in form.relatedAssets" :key="index">
						<view class="asset-info">
							<text class="asset-name">{{ asset.assetName }}</text>
							<text class="asset-no">{{ asset.assetNo }}</text>
						</view>
						<text class="remove-btn" @tap="removeAsset(index)">×</text>
					</view>
					<view class="add-asset-btn" @tap="selectAssets">
						<text class="add-icon">+</text>
						<text class="add-text">快速选择</text>
					</view>
				</view>
			</view>

			<!-- 备件图片部分 -->
			<view class="section">
				<view class="section-title">备件图片</view>
				<view class="image-upload-tip">最多上传5张,单张不大于2MB。</view>
				<view class="image-list">
					<view class="image-item" v-for="(image, index) in previewImages" :key="index">
						<image :src="image" class="uploaded-image" mode="aspectFill"></image>
						<text class="remove-image" @tap="removeImage(index)">×</text>
					</view>
					<view class="upload-btn" @tap="chooseImage" v-if="form.images.length < 5">
						<text class="upload-icon">+</text>
					</view>
				</view>
			</view>

			<button class="submit" @tap="submit">提交</button>
		</view>
	</view>
</template>

<script>
import { addPart, uploadPartImage } from '@/api/inventory/part.js'
import { listWarehouseDTO } from '@/api/inventory/warehouse.js'
import { listPartType } from '@/api/dict/partType.js'

export default {
	data(){
		return { 
			form:{ 
				partNo:'', 
				partName:'', 
				modelNo:'', 
				partType:'', 
				warehouseCode:'', 
				relatedAssets: [],
				images: []
			}, 
			typeList:[], 
			warehouseList:[], 
			typeName:'', 
			warehouseName:'' 
		}
	},
	computed: {
		// 预览图片列表，构建完整的图片URL
		previewImages() {
			const minioBase = uni.getStorageSync('MINIO_BASE') || 'https://io.brightholdings.cn'
			const bucket = 'smart-maintenance'
			return (this.form.images || []).map(imageUrl => {
				if (!imageUrl) return '/static/banner-bg.jpg'
				if (/^https?:\/\//i.test(imageUrl)) return imageUrl
				// 使用MinIO方式构建图片URL
				return `${minioBase.replace(/\/$/, '')}/${bucket}/${imageUrl}`
			})
		}
	},
	onLoad(){ this.loadMeta() },
	methods:{
		async loadMeta(){
			uni.showLoading({ title: '加载中...' })
			
			// 加载备件类型
			try{ 
				const r = await listPartType({}); 
				console.log('备件类型API返回:', r)
				
				// 使用正确的API获取备件类型数据
				if (r && r.code === 200 && r.rows && Array.isArray(r.rows)) {
					this.typeList = r.rows.map(d => ({
						code: d.code || d.id,
						name: d.name || d.label
					}))
					console.log('备件类型处理完成:', this.typeList)
				} else if (r && r.code === 200 && r.data && Array.isArray(r.data)) {
					this.typeList = r.data.map(d => ({
						code: d.code || d.id,
						name: d.name || d.label
					}))
					console.log('备件类型处理完成:', this.typeList)
				} else {
					console.log('备件类型数据为空或格式不正确')
					this.typeList = []
				}
			}catch(e){
				console.error('加载备件类型失败:', e)
				this.typeList = []
				uni.showToast({ title: '加载备件类型失败', icon: 'none' })
			}
			
			// 加载仓库列表
			try{ 
				const r = await listWarehouseDTO({}); 
				console.log('仓库API返回:', r)
				
				// 只使用后端返回的真实数据
				if (r && r.code === 200 && r.data && Array.isArray(r.data)) {
					this.warehouseList = r.data.map(w => ({
						code: w.code || w.id || w.warehouseCode || '',
						name: w.name || w.warehouseName || w.label || w.text
					}))
					console.log('仓库列表处理完成:', this.warehouseList)
				} else {
					console.log('仓库数据为空或格式不正确')
					this.warehouseList = []
				}
			}catch(e){
				console.error('加载仓库列表失败:', e)
				this.warehouseList = []
				uni.showToast({ title: '加载仓库列表失败', icon: 'none' })
			}
			
			uni.hideLoading()
		},
		onTypeChange(e){ const it=this.typeList[Number(e.detail.value)]; if(it){ this.form.partType=it.code; this.typeName=it.name } },
		onWhChange(e){ const it=this.warehouseList[Number(e.detail.value)]; if(it){ this.form.warehouseCode=it.code; this.warehouseName=it.name } },
		
		// 选择资产
		selectAssets(){
			uni.navigateTo({
				url: '/pages/asset/list?selectMode=true'
			})
		},
		
		// 移除资产
		removeAsset(index){
			this.form.relatedAssets.splice(index, 1)
		},
		
		// 选择图片
		chooseImage(){
			uni.chooseImage({
				count: 5 - this.form.images.length,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					console.log('选择的图片:', res.tempFilePaths)
					this.uploadImages(res.tempFilePaths)
				},
				fail: (err) => {
					console.error('选择图片失败:', err)
					uni.showToast({ title: '选择图片失败', icon: 'none' })
				}
			})
		},
		
		// 上传图片
		async uploadImages(filePaths){
			uni.showLoading({ title: '上传中...' })
			try {
				for(let i = 0; i < filePaths.length; i++){
					const filePath = filePaths[i]
					console.log(`上传第${i+1}张图片:`, filePath)
					
					// 检查文件大小
					const fileInfo = await this.getFileInfo(filePath)
					if(fileInfo.size > 2 * 1024 * 1024) {
						uni.showToast({ title: `第${i+1}张图片超过2MB`, icon: 'none' })
						continue
					}
					
					const fileName = await uploadPartImage(filePath)
					console.log('上传成功，文件名:', fileName)
					
					// 直接存储文件名，让previewImages计算属性处理URL构建
					this.form.images.push(fileName)
					console.log('添加图片文件名:', fileName)
				}
				uni.hideLoading()
				uni.showToast({ title: '上传成功', icon: 'success' })
			} catch(e) {
				console.error('上传图片失败:', e)
				uni.hideLoading()
				uni.showToast({ title: '上传失败: ' + (e.message || '未知错误'), icon: 'none' })
			}
		},
		
		// 获取文件信息
		getFileInfo(filePath) {
			return new Promise((resolve, reject) => {
				uni.getFileInfo({
					filePath,
					success: resolve,
					fail: reject
				})
			})
		},
		
		// 移除图片
		removeImage(index){
			this.form.images.splice(index, 1)
		},
		
		async submit(){
			try{
				// 验证必填字段
				if(!this.form.partNo) {
					uni.showToast({ title: '请输入备件编号', icon: 'none' })
					return
				}
				if(!this.form.partName) {
					uni.showToast({ title: '请输入备件名称', icon: 'none' })
					return
				}
				if(!this.form.modelNo) {
					uni.showToast({ title: '请输入规格型号', icon: 'none' })
					return
				}
				if(!this.form.partType) {
					uni.showToast({ title: '请选择备件类型', icon: 'none' })
					return
				}
				if(!this.form.warehouseCode) {
					uni.showToast({ title: '请选择仓库', icon: 'none' })
					return
				}
				
				const payload={ 
					partNo: this.form.partNo,
					partName: this.form.partName, // PartDTO期望partName字段
					specNo: this.form.modelNo, // 后端期望specNo字段
					partTypeCode: this.form.partType, // 后端期望partTypeCode字段
					warehouseCode: this.form.warehouseCode,
					associatedAssetsJson: this.form.relatedAssets.length > 0 ? JSON.stringify(this.form.relatedAssets) : '', // 后端期望associatedAssetsJson字段
					imageUrls: this.form.images.length > 0 ? JSON.stringify(this.form.images) : '' // 将图片数组转换为JSON字符串
				}
				
				console.log('提交数据:', payload)
				console.log('提交数据长度:', JSON.stringify(payload).length)
				console.log('图片数据:', this.form.images)
				console.log('关联资产数据:', this.form.relatedAssets)
				
				const r = await addPart(payload)
				console.log('提交响应:', r)
				
				if(!r || (r.code!==undefined && r.code!==200)) {
					console.error('提交失败，响应:', r)
					return uni.showToast({title:r.msg||'提交失败',icon:'none'})
				}
				uni.showToast({ title:'新增成功', icon:'success' });
				setTimeout(()=>uni.navigateBack({delta:1}),600)
			}catch(e){ 
				console.error('提交失败:', e)
				uni.showToast({ title:'提交失败: ' + (e.message || '未知错误'), icon:'none' }) 
			}
		}
	},
	
	// 监听页面返回，处理资产选择结果
	onShow(){
		// 检查是否有选中的资产数据
		const selectedAssets = uni.getStorageSync('selectedAssets')
		if(selectedAssets && selectedAssets.length > 0){
			// 合并选中的资产，避免重复
			selectedAssets.forEach(asset => {
				const exists = this.form.relatedAssets.find(item => item.assetNo === asset.assetNo)
				if(!exists){
					this.form.relatedAssets.push(asset)
				}
			})
			// 清除存储的选择数据
			uni.removeStorageSync('selectedAssets')
		}
	}
}
</script>

<style>
.container{min-height:100vh;background:#f6f7fb}
.status-bar{height:var(--status-bar-height)}
.header{padding:16rpx 24rpx}
.title{font-size:36rpx;font-weight:700}
.card{margin:16rpx;border-radius:16rpx;background:#fff;box-shadow:0 6rpx 20rpx rgba(0,0,0,.06)}
.form{padding:24rpx}
.field{margin-bottom:28rpx}
.label{display:block;color:#666;margin-bottom:10rpx;font-size:26rpx}
.input{border:1rpx solid #e5e5e5;border-radius:12rpx;padding:18rpx;background:#fafafa}
.picker{color:#333}
.submit{margin-top:24rpx;background:#007aff;color:#fff}

/* 新增样式 */
.section{margin-top:32rpx;padding-top:24rpx;border-top:1rpx solid #f0f0f0}
.section-title{font-size:32rpx;font-weight:600;color:#333;margin-bottom:20rpx}


/* 关联资产样式 */
.asset-list{display:flex;flex-direction:column}
.asset-item{display:flex;align-items:center;justify-content:space-between;padding:16rpx;background:#f8f9fa;border-radius:8rpx;margin-bottom:12rpx}
.asset-info{flex:1}
.asset-name{display:block;font-size:28rpx;color:#333;font-weight:500}
.asset-no{display:block;font-size:24rpx;color:#666;margin-top:4rpx}
.remove-btn{width:40rpx;height:40rpx;border-radius:50%;background:#ff4757;color:#fff;display:flex;align-items:center;justify-content:center;font-size:24rpx;font-weight:bold}
.add-asset-btn{display:flex;align-items:center;justify-content:center;padding:20rpx;border:2rpx dashed #007aff;border-radius:8rpx;background:#f0f8ff}
.add-icon{font-size:32rpx;color:#007aff;margin-right:8rpx}
.add-text{font-size:28rpx;color:#007aff}

/* 图片上传样式 */
.image-upload-tip{font-size:24rpx;color:#999;margin-bottom:16rpx}
.image-list{display:flex;flex-wrap:wrap;gap:12rpx}
.image-item{position:relative;width:120rpx;height:120rpx;border-radius:8rpx;overflow:hidden}
.uploaded-image{width:100%;height:100%}
.remove-image{position:absolute;top:-8rpx;right:-8rpx;width:32rpx;height:32rpx;border-radius:50%;background:#ff4757;color:#fff;display:flex;align-items:center;justify-content:center;font-size:20rpx;font-weight:bold}
.upload-btn{width:120rpx;height:120rpx;border:2rpx dashed #ddd;border-radius:8rpx;display:flex;align-items:center;justify-content:center;background:#fafafa}
.upload-icon{font-size:48rpx;color:#999}
</style>

